﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using lindyaka.Domain;
using lindyaka.Library;
using lindyaka.Repository.Interfaces;

namespace lindyaka.Repository.Entities
{
    public class Role : IRoleRepository, IDisposable
    {
        private DatabaseContext _db;

        public Role()
        {
            _db = new DatabaseContext();
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        public void Add(Domain.Entities.Role role)
        {
            _db.Roles.Add(role);
            _db.SaveChanges();
        }

        public void Remove(Expression<Func<Domain.Entities.Role, bool>> query)
        {
            _db.Roles.RemoveRange(_db.Roles.Where(query).AsEnumerable());
            _db.SaveChanges();
        }

        public void Update(Domain.Entities.Role role)
        {
            Domain.Entities.Role entry = Find(r => r.RoleId == role.RoleId);
            Entity.Merge(entry, role);
            _db.SaveChanges();
        }

        public IEnumerable<Domain.Entities.Role> FindAll()
        {
            return ((from roles in _db.Roles select roles).AsEnumerable());
        }

        public Domain.Entities.Role Find(Expression<Func<Domain.Entities.Role, bool>> query)
        {
            // todo: check if more than one result is found, throw warning?
            return _db.Roles.Where(query).FirstOrDefault();
        }

        public IEnumerable<Domain.Entities.Role> FindMany(Expression<Func<Domain.Entities.Role, bool>> query)
        {
            return _db.Roles.Where(query).AsEnumerable();
        }

        protected void Dispose(bool disposing)
        {
            if ((!disposing) && (_db == null))
            {
                return;
            }
            _db.Dispose();
            _db = null;
        }
    }
}